package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wmUser.dtos.WmMaterialDto;
import com.heima.model.wmUser.pojos.WmMaterial;
import com.heima.model.wmUser.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    private FileStorageService fileStorageService;

    @Value("${file.oss.prefix}")
    private String prefix;

    @Value("${file.oss.web-site}")
    private String website;

    @Value("${file.oss.bucket-name}")
    private String bucketName;

    /**
     * 自媒体用户上传素材
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //检查参数（文件是否为空，文件大小是否为空）
        if (multipartFile == null || multipartFile.getSize() == 0) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID, "请上传正确的文件！！！！");
        }
        //判断用户是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null || user.getId() == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN, "请先登录！！！");
        }
        Integer uid = user.getId();
        //获取原始文件名称
        String originalFilename = multipartFile.getOriginalFilename();
        //获取文件的后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //通过uuid自动生成新的文件名
        String uuid = UUID.randomUUID().toString();
        //uuid自动生成的文件名中间会有横杠隔开，因此需要去除横杠
        String s = StringUtils.replaceAll(uuid, "-", "");
        String fileName = s + suffix;
        //新建一个素材对象用于上传素材
        WmMaterial material = new WmMaterial();
        try {
            //获取文件在oss中的全路径
            String store = fileStorageService.store(prefix, fileName, multipartFile.getInputStream());
            //封装对象
            material.setUrl(store);
            material.setUserId(uid);
            material.setType((short) 0);
            material.setIsCollection((short) 0);
            material.setCreatedTime(new Date());
            //往数据库中添加上传的图片信息
            save(material);
            //拼接出上传文件的全路径，用于前端回显
            material.setUrl(website + store);
            return ResponseResult.okResult(material);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("上传文件失败   ===> {}", e.getMessage());
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR, "图片上传失败！！！");
        }
    }

    /**
     * 加载素材列表
     */
    @Override
    public ResponseResult findMaterialList(WmMaterialDto wmMaterialDto) {
        //检查数据是否合法
        if (wmMaterialDto == null || StringUtils.isBlank(wmMaterialDto.getIsCollection())) {
            CustomException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        wmMaterialDto.checkParam();
        //获取当前用户的id
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null || user.getId() == null) {
            CustomException.cust(AppHttpCodeEnum.NEED_LOGIN, "请先登录！！！！");
        }
        //获取分页查询的对象
        Page<WmMaterial> page = new Page<>(wmMaterialDto.getPage(), wmMaterialDto.getSize());
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(WmMaterial::getIsCollection, wmMaterialDto.getIsCollection())
                .eq(WmMaterial::getUserId, user.getId())
                .orderByDesc(WmMaterial::getCreatedTime);
        //获取分页查询结果
        IPage<WmMaterial> iPage = page(page, wrapper);
        //封装返回结果
        PageResponseResult responseResult = new PageResponseResult(wmMaterialDto.getPage(), wmMaterialDto.getSize(), iPage.getTotal());
        List<WmMaterial> records = iPage.getRecords();
        for (WmMaterial record : records) {
            record.setUrl( website + record.getUrl());
        }
        responseResult.setData(records);
        return responseResult;
    }

    /**
     * 根据图片id删除图片
     */
    @Override
    public ResponseResult delPictureById(Integer id) {
        //检查数据是否合法
        if (id == null) {
            CustomException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取当前登录的用户
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null || user.getId() == null) {
            CustomException.cust(AppHttpCodeEnum.NEED_LOGIN, "请先去登录！！！！");
        }
        //判断数据库中是否存在该图片
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getId, id).eq(WmMaterial::getUserId, user.getId());
        WmMaterial material = getOne(wrapper);
        if (material == null) {
            CustomException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "当前素材不存在！！！！");
        }
        removeById(id);
        //删除阿里云上的图片
        fileStorageService.delete(material.getUrl());
        return ResponseResult.okResult();
    }

    /**
     * 收藏与取消收藏图片
     */
    @Override
    public ResponseResult isCollection(Integer id) {
        //判断数据是否合法
        if (id == null) {
            CustomException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断当前登录的用户
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null || user.getId() == null) {
            CustomException.cust(AppHttpCodeEnum.NEED_LOGIN, "请先登录！！！");
        }
        Integer uid = user.getId();
        //判断数据库中是否有该素材
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getId, id).eq(WmMaterial::getUserId, uid);
        WmMaterial material = getOne(wrapper);
        if (material == null) {
            CustomException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        material.setIsCollection((short) ((material.getIsCollection() + 1) % 2));
        updateById(material);
        return ResponseResult.okResult();
    }
}

